import type { UseFetchOptions } from "nuxt/app";

interface ResponseData<T> {
  code: number;
  message: string;
  data: T;
  success: boolean;
}

interface ParamsType {
  [key: string]: any;
}

const errorMessages: any = {
  404: "资源找不到",
  500: "服务器内部错误",
};

// 从 .env.xxx 文件中读取到请求前缀
const baseURL = import.meta.env.VITE_BASE_URL;

async function request<T>(
  url: string,
  options?: UseFetchOptions<ResponseData<T>>
) {
  // 1. 设置公共请求前缀
  const { data, error } = await useFetch(baseURL + url, options);

  // 请求失败
  if (error.value) {
    const message = error.value.statusCode
      ? errorMessages[error.value.statusCode]
      : "未知错误";
    // 提示错误
    // console.log(message);
    ElMessage.error(message);
    return Promise.reject(message);
  }

  // 请求成功
  if (data.value!.code === 200) {
    // 功能成功
    return Promise.resolve(data.value!.data);
  } else {
    // 功能失败
    const message = data.value!.message;
    // console.log(message);
    ElMessage.error(message);
    return Promise.reject(message);
  }
}

class Http {
  get<T>(url: string, params: ParamsType = {}) {
    return request<T>(url, {
      params,
      method: "get",
    });
  }
  post<T>(url: string, body: ParamsType = {}) {
    return request<T>(url, {
      body,
      method: "post",
    });
  }
  put<T>(url: string, body: ParamsType = {}) {
    return request<T>(url, {
      body,
      method: "put",
    });
  }
  delete<T>(url: string, params: ParamsType = {}) {
    return request<T>(url, {
      params,
      method: "delete",
    });
  }
}

export default new Http();
